//
//  XAsyncAxisView.m
//  RuiHeApp
//
//  Created by Jun on 2022/12/16.
//

#import "XAsyncAxisView.h"
#import <YYAsyncLayer/YYAsyncLayer.h>
#import "DevChartModel.h"
#import "DeviceChartFieldModel.h"

#define topMargin 25   // 为顶部留出的空白
#define kChartLineColor         [UIColor grayColor]
#define kChartTextColor         [UIColor blackColor]
#define pointColor              [UIColor colorWithRed:27/255.0 green:168/255.0 blue:248/255.0 alpha:.5]
#define leftMargin 15
#define rightMargin 15
#define sideSpace 15
#define wsRGBA(r, g, b, a) ([UIColor colorWithRed:(r / 255.0) green:(g / 255.0) blue:(b / 255.0) alpha:a])
//字体颜色
#define kFontColor(color)  [UIColor colorWithHexString:color]



@interface XAsyncAxisView ()<YYAsyncLayerDelegate>

@property (strong, nonatomic) NSArray *xTitleArray;
@property (strong, nonatomic) NSArray *yValueArray;
@property (strong, nonatomic) NSDictionary *yValueDic;
@property (assign, nonatomic) CGFloat yMax;
@property (assign, nonatomic) CGFloat yMin;
@property (strong, nonatomic) NSString *xTypeName;
@property (strong, nonatomic) NSString *yTypeName;
@property (strong, nonatomic) NSString *unit;

@property (assign, nonatomic) CGFloat defaultSpace;//X轴点之间的间隔

/**
 *  记录坐标轴的第一个frame
 */
@property (assign, nonatomic) CGRect firstFrame;
@property (assign, nonatomic) CGRect firstStrFrame;//第一个点的文字的frame


@end



@implementation XAsyncAxisView

+ (Class)layerClass {
    return YYAsyncLayer.class;
}

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        self.xTitleArray = @[];
        self.yValueArray = @[];
        self.yMax = .0;
        self.yMin = .0;
        self.xTypeName = @"";
        self.yTypeName = @"";
        self.unit = @"";
        self.defaultSpace = 0;
        self.pointGap = 0;
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,self.frame.size.height-30,self.frame.size.width,30)];
        [view setBackgroundColor:UIColor.orangeColor];
        [self addSubview:view];
        
    }
    return self;
}


- (id)initWithFrame:(CGRect)frame xTitleArray:(NSArray*)xTitleArray yValueArray:(NSArray*)yValueArray yMax:(CGFloat)yMax yMin:(CGFloat)yMin yTypeName:(NSString*)yTypeName xTypeName:(NSString*)xTypeName  unit:(NSString*)unit {

    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        self.xTitleArray = xTitleArray;
        self.yValueArray = yValueArray;
        self.yMax = yMax;
        self.yMin = yMin;
        self.xTypeName = xTypeName;
        self.yTypeName = yTypeName;
        self.unit = unit;
        
        if (xTitleArray.count > 600) {
            _defaultSpace = 5;
        }
        else if (xTitleArray.count > 400 && xTitleArray.count <= 600){
            _defaultSpace = 10;
        }
        else if (xTitleArray.count > 200 && xTitleArray.count <= 400){
            _defaultSpace = 20;
        }
        else if (xTitleArray.count > 100 && xTitleArray.count <= 200){
            _defaultSpace = 30;
        }
        else if (xTitleArray.count > 10 && xTitleArray.count <= 100){
            _defaultSpace = 40;
        }
        else {
            _defaultSpace = (wsScreenWidth-leftMargin-rightMargin-sideSpace*2)/(xTitleArray.count-1);
        }


        self.pointGap = (wsScreenWidth-leftMargin-rightMargin-sideSpace*2)/(xTitleArray.count-1);
        
    }
    
    return self;
}

- (id)initWithFrame:(CGRect)frame xTitleArray:(NSArray*)xTitleArray yValueDic:(NSDictionary*)yValueDic yMax:(CGFloat)yMax yMin:(CGFloat)yMin yTypeName:(NSString*)yTypeName xTypeName:(NSString*)xTypeName  unit:(NSString*)unit{
    
    
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        self.xTitleArray = xTitleArray;
        self.yValueDic = yValueDic;
        self.yMax = yMax;
        self.yMin = yMin;
        self.xTypeName = xTypeName;
        self.yTypeName = yTypeName;
        self.unit = unit;
        
        if (xTitleArray.count > 600) {
            _defaultSpace = 5;
        }
        else if (xTitleArray.count > 400 && xTitleArray.count <= 600){
            _defaultSpace = 10;
        }
        else if (xTitleArray.count > 200 && xTitleArray.count <= 400){
            _defaultSpace = 20;
        }
        else if (xTitleArray.count > 100 && xTitleArray.count <= 200){
            _defaultSpace = 30;
        }
        else if (xTitleArray.count > 10 && xTitleArray.count <= 100){
            _defaultSpace = 40;
        }
        else {
            _defaultSpace = (wsScreenWidth-leftMargin-rightMargin-sideSpace*2)/(xTitleArray.count-1);
        }


        self.pointGap = (wsScreenWidth-leftMargin-rightMargin-sideSpace*2)/(xTitleArray.count-1);
        
        
    }
    
    return self;
}


- (void)setPointGap:(CGFloat)pointGap {
    _pointGap = pointGap;
    [self commitTransaction];
}

- (void)setIsLongPress:(BOOL)isLongPress {
    _isLongPress = isLongPress;
    //[self commitTransaction];
    [self.layer setNeedsDisplay];
}

- (void)setChartModel:(DevChartModel *)chartModel{
    _chartModel = chartModel;
    _xTitleArray = _chartModel.xTitlesArray;
    
    if (_xTitleArray.count > 600) {
        _defaultSpace = 5;
    }
    else if (_xTitleArray.count > 400 && _xTitleArray.count <= 600){
        _defaultSpace = 10;
    }
    else if (_xTitleArray.count > 200 && _xTitleArray.count <= 400){
        _defaultSpace = 20;
    }
    else if (_xTitleArray.count > 100 && _xTitleArray.count <= 200){
        _defaultSpace = 30;
    }
    else if (_xTitleArray.count > 10 && _xTitleArray.count <= 100){
        _defaultSpace = 40;
    }
    else {
        _defaultSpace = (self.frame.size.width-sideSpace*2)/(_xTitleArray.count-1);
    }
    self.pointGap = (self.frame.size.width-sideSpace*2)/(_xTitleArray.count-1);
    
    [self commitTransaction];
}


- (void)contentsNeedUpdated {
    self.layer.contentsScale = [UIScreen mainScreen].scale;
    [self.layer setNeedsDisplay];
}

- (void)commitTransaction {
    [[YYTransaction transactionWithTarget:self selector:@selector(contentsNeedUpdated)] commit];
}

- (YYAsyncLayerDisplayTask *)newAsyncDisplayTask {
    YYAsyncLayerDisplayTask *task = [YYAsyncLayerDisplayTask new];
    task.willDisplay = ^(CALayer * _Nonnull layer) {
       
    };
    
    task.display = ^(CGContextRef  _Nonnull context, CGSize size, BOOL (^ _Nonnull isCancelled)(void)) {
        if (isCancelled()) {
            return;
        }
        // 在这里进行异步绘制
        [self draw:context size:size];
    };
    task.didDisplay = ^(CALayer * _Nonnull layer, BOOL finished) {
        if (finished) {
           
        } else {
           
        }
    };
    return task;
}


- (void)draw:(CGContextRef)context size:(CGSize)size{
    //CGContextRef context = UIGraphicsGetCurrentContext();
    if (_chartModel.selectArray.count>0) {
        for (DeviceChartFieldModel *model in _chartModel.selectArray) {
            if (model.isShowLine&&model.dataArray.count>0) {
                [self drawShadow:model size:size];//画渐变色背景
            }
        }
    }
    
    //////////////// 画原点上的x轴 ///////////////////////
    NSDictionary *attribute = @{NSFontAttributeName : [UIFont systemFontOfSize:10]};
    CGSize textSize = [@"22-22\r\n22:22" sizeWithAttributes:attribute];
    
    [self drawLine:context
        startPoint:CGPointMake(sideSpace, size.height - textSize.height - 5)
          endPoint:CGPointMake(size.width-sideSpace, size.height - textSize.height - 5)
         lineColor:[UIColor grayColor]
         lineWidth:1];
    
    //////////////// 画横向分割线 ///////////////////////
    CGFloat separateMargin = (size.height - topMargin - textSize.height - 5 - 5 * 1) / 5;
    for (int i = 0; i < 5; i++) {
        [self drawLine:context
            startPoint:CGPointMake(sideSpace, size.height - textSize.height - 5  - (i + 1) *(separateMargin + 1))
              endPoint:CGPointMake(size.width-sideSpace, size.height - textSize.height - 5  - (i + 1) *(separateMargin + 1))
             lineColor:[UIColor lightGrayColor]
             lineWidth:.3];
    }
    
    
    
    ////////////////////// X轴文字 //////////////////////////
    // 添加坐标轴Label
    for (int i = 0; i < self.xTitleArray.count; i++) {
        NSString *title = self.xTitleArray[i];
        title = [title stringByReplacingOccurrencesOfString:@" " withString:@"\r\n"];
        
        [[UIColor blackColor] set];
        NSDictionary *attr = @{NSFontAttributeName : [UIFont systemFontOfSize:10]};
        CGSize labelSize = [title sizeWithAttributes:attr];
        
        CGRect titleRect = CGRectMake(sideSpace+(i) * self.pointGap - labelSize.width / 2,size.height - labelSize.height,labelSize.width,labelSize.height);
        
        if (i == 0) {
            self.firstFrame = titleRect;
            //if (titleRect.origin.x < 0) {
                //titleRect.origin.x = 0;
            //}
            
            [title drawInRect:titleRect withAttributes:@{NSFontAttributeName :[UIFont systemFontOfSize:10],NSForegroundColorAttributeName:kChartTextColor}];
            
            //画垂直X轴的竖线
            [self drawLine:context
                startPoint:CGPointMake(titleRect.origin.x+labelSize.width/2, size.height - labelSize.height-5)
                  endPoint:CGPointMake(titleRect.origin.x+labelSize.width/2, size.height - labelSize.height-10)
                 lineColor:kChartLineColor
                 lineWidth:1];
//        }else if (i == self.xTitleArray.count-1){
//
//            self.firstFrame = titleRect;
//            [title drawInRect:titleRect withAttributes:@{NSFontAttributeName :[UIFont systemFontOfSize:10],NSForegroundColorAttributeName:kChartTextColor}];
//
//            //画垂直X轴的竖线
//            [self drawLine:context
//                startPoint:CGPointMake(titleRect.origin.x+labelSize.width/2, self.frame.size.height - labelSize.height-5)
//                  endPoint:CGPointMake(titleRect.origin.x+labelSize.width/2, self.frame.size.height - labelSize.height-10)
//                 lineColor:kChartLineColor
//                 lineWidth:1];
        }else{
            CGFloat maxX = CGRectGetMaxX(self.firstFrame);
            if ((maxX + 5) > titleRect.origin.x) {
                //不绘制
            }else{

                [title drawInRect:titleRect withAttributes:@{NSFontAttributeName :[UIFont systemFontOfSize:10],NSForegroundColorAttributeName:kChartTextColor}];
                //画垂直X轴的竖线
                [self drawLine:context
                    startPoint:CGPointMake(titleRect.origin.x+labelSize.width/2, size.height - labelSize.height-5)
                      endPoint:CGPointMake(titleRect.origin.x+labelSize.width/2, size.height - labelSize.height-10)
                     lineColor:kChartLineColor
                     lineWidth:1];

                self.firstFrame = titleRect;
            }
        }
    }
    
    
    //////////////// 画曲线 ///////////////////////
    if (_chartModel.selectArray.count>0) {
        for (DeviceChartFieldModel *model in _chartModel.selectArray) {
            if (model.isShowLine&&model.dataArray.count>0) {
                [self drawLine:context valueModel:model size:size];
            }
        }
    }
    
    
    //////////////// 画长按交叉线 ///////////////////////
    [self drawCrossLine:context size:size];
    
}

- (void)drawShadow:(DeviceChartFieldModel *)model size:(CGSize)size{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGMutablePathRef path = CGPathCreateMutable();
    NSDictionary *attribute = @{NSFontAttributeName : [UIFont systemFontOfSize:10]};
    CGSize textSize = [@"22-22\r\n22:22" sizeWithAttributes:attribute];
    
    //CGPathMoveToPoint(path, NULL, self.pointGap, self.frame.size.height - textSize.height-5);
    CGPathMoveToPoint(path, NULL,sideSpace,size.height - textSize.height-5);
    NSNumber *startValue = model.dataArray[0];
    CGFloat chartHeight = size.height - textSize.height - 5 - topMargin;

    CGPoint firstStartPoint = CGPointMake(sideSpace, chartHeight -  (startValue.floatValue-model.y_min)/(model.y_max-model.y_min) * chartHeight+topMargin);
    

    CGPathAddCurveToPoint(path,  NULL,(sideSpace+firstStartPoint.x)/2, sideSpace, (sideSpace+firstStartPoint.x)/2, firstStartPoint.y, firstStartPoint.x, firstStartPoint.y);
    //画折线
    for (NSInteger i = 0; i < model.dataArray.count; i++) {
        CGFloat chartHeight = size.height - textSize.height - 5 - topMargin;
        NSNumber *startValue = model.dataArray[i];
        
        CGPoint startPoint = CGPointMake(sideSpace+(i)*self.pointGap, chartHeight -  (startValue.floatValue-model.y_min)/(model.y_max-model.y_min) * chartHeight+topMargin);
    
        if (i == model.dataArray.count-1) {
            CGPathAddLineToPoint(path, NULL, startPoint.x,startPoint.y);
        }else {
            
            NSNumber *endValue = model.dataArray[i+1];
            CGPoint endPoint = CGPointMake(sideSpace+(i+1)*self.pointGap, chartHeight -  (endValue.floatValue-model.y_min)/(model.y_max-model.y_min) * chartHeight+topMargin);
            CGPathAddCurveToPoint(path,  NULL,(startPoint.x+endPoint.x)/2, startPoint.y, (startPoint.x+endPoint.x)/2, endPoint.y, endPoint.x, endPoint.y);
        }
        
    }
    
    CGPathAddLineToPoint(path, NULL, sideSpace+self.pointGap*(model.dataArray.count-1), size.height - textSize.height-5);
    CGPathCloseSubpath(path);
    
    //绘制渐变
    [self drawLinearGradient:context path:path startColor:[kCOLOR_HEX(model.colorStr) colorWithAlphaComponent:0.2].CGColor endColor:[UIColor whiteColor].CGColor];
    //注意释放CGMutablePathRef
    CGPathRelease(path);
}


- (UIColor *)randomColor {
    int R = (arc4random() % 256) ;
    int G = (arc4random() % 256) ;
    int B = (arc4random() % 256) ;
    return [UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:0.3];
}

/////////////////////// 根据数据源画折线 /////////////////////////
- (void)drawLine:(CGContextRef)context valueModel:(DeviceChartFieldModel *)model size:(CGSize)size{
    NSDictionary *attribute = @{NSFontAttributeName : [UIFont systemFontOfSize:10]};
    CGSize textSize = [@"22-22\r\n22:22" sizeWithAttributes:attribute];
    if (model.dataArray && model.dataArray.count > 0) {

        //画折线
        for (NSInteger i = 0; i < model.dataArray.count; i++) {
            
            //如果是最后一个点
            if (i == model.dataArray.count-1) {
                
                NSNumber *endValue = model.dataArray[i];
                CGFloat chartHeight = size.height - textSize.height - 5 - topMargin;
                CGPoint endPoint = CGPointMake(sideSpace+(i)*self.pointGap, chartHeight -  (endValue.floatValue-model.y_min)/(model.y_max-model.y_min) * chartHeight+topMargin);

                //画最后一个点
                UIColor*aColor = kCOLOR_HEX(model.colorStr); //点的颜色
                CGContextSetFillColorWithColor(context, aColor.CGColor);//填充颜色
                CGContextAddArc(context, endPoint.x, endPoint.y, 0.5, 0, 2*M_PI, 0); //添加一个圆
                CGContextDrawPath(context, kCGPathFill);//绘制填充

                
                //画点上的文字
                NSString *str = [self removeZeroInFloatString:[NSString stringWithFormat:@"%@",endValue]];
                
                NSDictionary *attr = @{NSFontAttributeName : [UIFont systemFontOfSize:10]};
                CGSize strSize = [str sizeWithAttributes:attr];
                
                CGRect strRect = CGRectMake(endPoint.x-strSize.width/2,endPoint.y-strSize.height,strSize.width,strSize.height);
                
                // 如果点的文字有重叠，那么不绘制
                CGFloat maxX = CGRectGetMaxX(self.firstStrFrame);
                if (i != 0) {
                    if ((maxX + 6) > strRect.origin.x) {
                        //不绘制
                    }else{
                        //[str drawInRect:strRect withAttributes:@{NSFontAttributeName :[UIFont systemFontOfSize:10],NSForegroundColorAttributeName:kChartTextColor}];
                        self.firstStrFrame = strRect;
                    }
                }else {
                    if (self.firstStrFrame.origin.x < 0) {
                        
                        CGRect frame = self.firstStrFrame;
                        frame.origin.x = 0;
                        self.firstStrFrame = frame;
                    }
                }

            }else {
                
                NSNumber *startValue = model.dataArray[i];
                NSNumber *endValue = model.dataArray[i+1];
                CGFloat chartHeight = size.height - textSize.height - 5 - topMargin;
                
                CGPoint startPoint = CGPointMake(sideSpace+(i)*self.pointGap, chartHeight -  (startValue.floatValue-model.y_min)/(model.y_max-model.y_min) * chartHeight+topMargin);
                
                CGPoint endPoint = CGPointMake(sideSpace+(i+1)*self.pointGap, chartHeight -  (endValue.floatValue-model.y_min)/(model.y_max-model.y_min) * chartHeight+topMargin);
                
                CGFloat normal[1]={1};
                CGContextSetLineDash(context,0,normal,0); //画实线
                
                [self drawLine:context startPoint:startPoint endPoint:endPoint lineColor:kCOLOR_HEX(model.colorStr) lineWidth:2];
                //画点
                UIColor*aColor = kCOLOR_HEX(model.colorStr); //点的颜色
                CGContextSetFillColorWithColor(context, aColor.CGColor);//填充颜色
                CGContextAddArc(context, startPoint.x, startPoint.y, 0.5, 0, 2*M_PI, 0); //添加一个圆
                CGContextDrawPath(context, kCGPathFill);//绘制填充
                
                
                if (!_isShowLabel) {
                    
                    //画点上的文字
                    NSString *str = [self removeZeroInFloatString:[NSString stringWithFormat:@"%@",startValue]];

                    
                    NSDictionary *attr = @{NSFontAttributeName : [UIFont systemFontOfSize:10]};
                    CGSize strSize = [str sizeWithAttributes:attr];
                    
                    CGRect strRect = CGRectMake(startPoint.x-strSize.width/2,startPoint.y-strSize.height,strSize.width,strSize.height);
                    if (i == 0) {
                        self.firstStrFrame = strRect;
                        if (strRect.origin.x < 0) {
                            strRect.origin.x = 0;
                        }
                        
                        //[str drawInRect:strRect withAttributes:@{NSFontAttributeName :[UIFont systemFontOfSize:10],NSForegroundColorAttributeName:kChartTextColor}];
                    }
                    // 如果点的文字有重叠，那么不绘制
                    CGFloat maxX = CGRectGetMaxX(self.firstStrFrame);
                    if (i != 0) {
                        if ((maxX + 6) > strRect.origin.x) {
                            
                        }else{
                            
                            //[str drawInRect:strRect withAttributes:@{NSFontAttributeName :[UIFont systemFontOfSize:10],NSForegroundColorAttributeName:kChartTextColor}];
                            
                            self.firstStrFrame = strRect;
                        }
                    }else {
                        if (self.firstStrFrame.origin.x < 0) {
                            
                            CGRect frame = self.firstStrFrame;
                            frame.origin.x = 0;
                            self.firstStrFrame = frame;
                        }
                    }
                }
            }
        }
    }
}


- (void)drawCrossLine:(CGContextRef)context size:(CGSize)size{
    
    if(self.isLongPress&&_chartModel.allDataArray.count>0)
    {
        NSDictionary *attribute = @{NSFontAttributeName : [UIFont systemFontOfSize:10]};
        CGSize textSize = [@"22-22\r\n22:22" sizeWithAttributes:attribute];
        CGFloat chartHeight = size.height - textSize.height - 5 - topMargin;
        
        int nowPoint = (_currentLoc.x-sideSpace)/self.pointGap;
        
        NSMutableArray *s_values = [NSMutableArray array];
        NSMutableArray *s_points = [NSMutableArray array];
        NSMutableArray *dataArray = [NSMutableArray array];
        NSMutableArray *colorsArray = [NSMutableArray array];
        CGFloat max_num = 0.0;
    
        
        if (_chartModel.selectArray.count>0) {
            for (DeviceChartFieldModel *model in _chartModel.selectArray) {
                if (model.isShowLine&&model.dataArray.count>0) {
                    if(nowPoint >= 0 && nowPoint < [model.dataArray count]) {
                        NSNumber *num = [model.dataArray objectAtIndex:nowPoint];
                        max_num = MAX(max_num, [num floatValue]);
                        [s_values addObject:num];
                        CGFloat piont_y = chartHeight -  (num.floatValue-model.y_min)/(model.y_max-model.y_min) * chartHeight+topMargin;
                        [s_points addObject:@(piont_y)];

                        [dataArray addObject:[NSString stringWithFormat:@"%@: %@%@", model.alias,[NSString stringWithFormat:@"%.1f",[num floatValue]],model.unitName]];
                        [colorsArray addObject:model.colorStr];
                    }else{
                        return;
                    }
                }
            }
        }
        
        NSString *dataStr = [dataArray componentsJoinedByString:@"\n"];
        NSString *timeStr = @"";
        if(nowPoint >= 0 && nowPoint < [self.xTitleArray count]) {
            timeStr = [NSString stringWithFormat:@"%@",self.xTitleArray[nowPoint]];
        }

        CGFloat timeWidth = [timeStr sizeWithAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:13],NSForegroundColorAttributeName:[UIColor whiteColor]}].width;
        CGFloat dataWidth = [dataStr sizeWithAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:10],NSForegroundColorAttributeName:[UIColor whiteColor]}].width;
        
        CGFloat with = timeWidth > dataWidth ? timeWidth : dataWidth;
        CGFloat shadowWith = with+20+15;
        
        CGContextSaveGState(context);
        
        CGPoint selectPoint = CGPointMake(sideSpace+(nowPoint)*self.pointGap, chartHeight - 0.5* chartHeight+topMargin);
        
        //画文字所在的位置  动态变化
        CGPoint drawPoint = CGPointZero;
        /*if(_screenLoc.x-shadowWith/2 > 0 && _screenLoc.x
           +shadowWith/2 < wsScreenWidth-leftMargin-rightMargin-sideSpace*2) {
            //如果按住的位置在屏幕靠右边边并且在屏幕靠上面的地方   那么字就显示在按住位置的左上角40 60位置
            drawPoint = CGPointMake(selectPoint.x-shadowWith/2, selectPoint.y-45);
        }
        else if(_screenLoc.x >((wsScreenWidth-leftMargin-rightMargin-sideSpace*2)/2)) {
            //如果按住的位置在屏幕靠右边边并且在屏幕靠上面的地方   那么字就显示在按住位置的左上角40 60位置
            drawPoint = CGPointMake(selectPoint.x-shadowWith-5, selectPoint.y-20);
        }
        else if (_screenLoc.x <= ((wsScreenWidth-leftMargin-rightMargin-sideSpace*2)/2)) {
            //如果按住的位置在屏幕靠左边边并且在屏幕靠上面的地方   那么字就显示在按住位置的右上角上角40 40位置
            drawPoint = CGPointMake(selectPoint.x+5, selectPoint.y-20);
        }*/
        
        if ((selectPoint.x+shadowWith+sideSpace)>size.width) {
            drawPoint = CGPointMake(selectPoint.x-shadowWith-5, selectPoint.y-20);
        }else{
            drawPoint = CGPointMake(selectPoint.x+5, selectPoint.y-20);
        }
    
        //画竖线
        [self drawLine:context startPoint:CGPointMake(selectPoint.x, topMargin) endPoint:CGPointMake(selectPoint.x, size.height-textSize.height - 5) lineColor:[UIColor lightGrayColor] lineWidth:1];
        
    
        NSInteger line_num = 15;
        if (_chartModel.selectArray.count>0) {
            for (DeviceChartFieldModel *model in _chartModel.selectArray) {
                if (model.isShowLine&&model.dataArray.count>0) {
                    if(nowPoint >= 0 && nowPoint < [model.dataArray count]) {
                        NSNumber *num = [model.dataArray objectAtIndex:nowPoint];
                        CGPoint point = CGPointMake(sideSpace+(nowPoint)*self.pointGap, chartHeight -  (num.floatValue-model.y_min)/(model.y_max-model.y_min) * chartHeight+topMargin);
                        // 交界点
                        CGRect myOval = {point.x-3, point.y-3, 6, 6};
                        CGContextSetFillColorWithColor(context, kFontColor(model.colorStr).CGColor);
                        CGContextAddEllipseInRect(context, myOval);
                        CGContextFillPath(context);
                    }else{
                        return;
                    }
                    line_num = line_num+15;
                }
            }
        }

        if(nowPoint >= 0 && nowPoint < [self.xTitleArray count]) {
            //设置数据背景，放在竖线之后加载，不会被竖线遮住
            CGContextSetFillColorWithColor(context, wsRGBA(1, 0, 0, 0.5).CGColor);
            CGPathRef clippath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(drawPoint.x, drawPoint.y, shadowWith, 15+line_num) cornerRadius:10].CGPath;
            CGContextAddPath(context, clippath);
            CGContextClosePath(context);
            CGContextDrawPath(context, kCGPathFill);
            self.shadowRect = CGRectMake(drawPoint.x, drawPoint.y, shadowWith, 15+line_num);

            [[NSString stringWithFormat:@"%@",self.xTitleArray[nowPoint]] drawInRect:CGRectMake(drawPoint.x+10, drawPoint.y+5, with, 15) withAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:13],NSForegroundColorAttributeName:[UIColor whiteColor]}];
            NSInteger i = 0;
            for (NSString *str in dataArray) {
                
                CGRect myOval = {drawPoint.x+10, drawPoint.y+20+5+15*i+1, 10, 10};
                CGContextSetFillColorWithColor(context, kFontColor(colorsArray[i]).CGColor);
                CGContextAddEllipseInRect(context, myOval);
                CGContextFillPath(context);
                
                [str drawInRect:CGRectMake(drawPoint.x+10+13, drawPoint.y+20+5+15*i, with,line_num) withAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:10],NSForegroundColorAttributeName:[UIColor whiteColor]}];
                i++;
            }
            
            /*[dataStr drawInRect:CGRectMake(drawPoint.x+10, drawPoint.y+20, with,line_num) withAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:10],NSForegroundColorAttributeName:[UIColor whiteColor]}];*/
        }
    }
}


- (void)drawLine:(CGContextRef)context startPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint lineColor:(UIColor *)lineColor lineWidth:(CGFloat)width {
    
    CGContextSetShouldAntialias(context, YES ); //抗锯齿
    CGColorSpaceRef Linecolorspace1 = CGColorSpaceCreateDeviceRGB();
    CGContextSetStrokeColorSpace(context, Linecolorspace1);
    CGContextSetLineWidth(context, width);
    CGContextSetStrokeColorWithColor(context, lineColor.CGColor);
    CGContextSetLineJoin(context,kCGLineJoinRound);
    CGContextMoveToPoint(context, startPoint.x, startPoint.y);
    //CGContextAddLineToPoint(context, endPoint.x, endPoint.y);
    if ((endPoint.x-startPoint.x)<width) {
        CGContextAddLineToPoint(context, endPoint.x, endPoint.y);
    }else{
    CGContextAddCurveToPoint(context, (startPoint.x+endPoint.x)/2, startPoint.y, (startPoint.x+endPoint.x)/2, endPoint.y, endPoint.x, endPoint.y);
    }
    CGContextStrokePath(context);
    CGColorSpaceRelease(Linecolorspace1);
}


- (void)drawLinearGradient:(CGContextRef)context path:(CGPathRef)path startColor:(CGColorRef)startColor endColor:(CGColorRef)endColor{

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGFloat locations[] = { 0.0, 1.0 };
    NSArray *colors = @[(__bridge id) startColor, (__bridge id) endColor];
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colors, locations);
    CGRect pathRect = CGPathGetBoundingBox(path);
    //具体方向可根据需求修改
    CGPoint startPoint = CGPointMake(CGRectGetMidX(pathRect), CGRectGetMinY(pathRect));
    CGPoint endPoint = CGPointMake(CGRectGetMidX(pathRect), CGRectGetMaxY(pathRect));
    CGContextSaveGState(context);
    CGContextAddPath(context, path);
    CGContextClip(context);
    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
    CGContextRestoreGState(context);
    CGGradientRelease(gradient);
    CGColorSpaceRelease(colorSpace);
}

//去掉小数点之后的无效0；
-(NSString*)removeZeroInFloatString:(NSString*)floatString {
    NSString *outNumber = [NSString stringWithFormat:@"%@",@(floatString.longLongValue)];
    return outNumber;
}
@end
